JavaScript, at its core, is a single-threaded language. This means it can only do one thing at a time. However, it handles complex tasks without freezing the browser using a model involving the JavaScript Engine, Call Stack, Web APIs, Callback Queue, and the Event Loop.
When you run JavaScript code, the JS Engine (like V8 in Chrome) creates a global execution context. This context has two phases:
undefined.The Call Stack is a data structure that keeps track of function calls. When a function is called, it's added (pushed) to the top of the stack. When it returns, it's removed (popped) from the stack.
function first() {
console.log("Entering first()");
second();
console.log("Exiting first()");
}
function second() {
console.log(" - Inside second()");
}
first(); // Start the process
What about asynchronous operations like setTimeout or fetching data? They don't block the call
stack.
setTimeout) is called, it's passed to a Web API in
the browser.| Concept | Purpose | Example |
|---|---|---|
| Call Stack | Manages synchronous function execution (First-In, Last-Out). | functionA() calls functionB(). |
| Web API | Handles browser-based async operations outside the JS engine. | setTimeout, fetch(), DOM events. |
| Callback Queue | Holds callback functions that are ready to be executed (First-In, First-Out). | The function inside setTimeout waits here. |
| Event Loop | Moves callbacks from the queue to the stack when the stack is empty. | The "bridge" between async and sync. |